package net.yeah.mickey_zhouyou.util.fcs.elem;

import java.util.ArrayList;
import java.util.List;

import javax.script.ScriptContext;

import net.yeah.mickey_zhouyou.util.fcs.serialize.IConvertor;

public class ConditionOr extends ConditionSelector {
	private ConditionSelector firstCondition;
	private ConditionSelector secondCondition;

	public ConditionOr(ConditionSelector firstCondition,
			ConditionSelector secondCondition) {
		super();
		this.firstCondition = firstCondition;
		this.secondCondition = secondCondition;
	}

	@Override
	public Object select(Object obj, IConvertor objConvertor,
			ScriptContext context) {
		if (obj == null)
			return null;
		Object o1 = this.firstCondition.select(obj, objConvertor, context);
		Object o2 = this.secondCondition.select(obj, objConvertor, context);
		if (o1 == null)
			return o2;
		if (o2 == null)
			return o1;
		if (o1 instanceof List && o2 instanceof List) {
			@SuppressWarnings("unchecked")
			List<Object> res = (List<Object>) o1;
			for (Object o : (List<?>) o2)
				res.add(o);
			return res;
		}
		if (o1 instanceof List) {
			@SuppressWarnings("unchecked")
			List<Object> res = (List<Object>) o1;
			res.add(o2);
			return res;
		}
		if (o2 instanceof List) {
			@SuppressWarnings("unchecked")
			List<Object> res = (List<Object>) o2;
			res.add(o1);
			return res;
		}
		List<Object> res = new ArrayList<Object>(2);
		res.add(o1);
		res.add(o2);
		return res;
	}

}
